package com.baykalcakici.cafepicker;

import java.util.List;

import org.joda.time.LocalTime;

import com.baykalcakici.cafepicker.dialog.VisitDialog;
import com.baykalcakici.cafepicker.picker.CafeListItem;
import com.baykalcakici.cafepicker.tasks.LoginTask;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

/**
 * Visit cafe Tab. Represents available cafes in a list view.
 */
public class VisitCafe extends ListActivity {
  private List<String> cafeNames;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
	  super.onCreate(savedInstanceState);
    setContentView(R.layout.visit_cafe);
    displayCafeNames();
  }

  @Override
  protected void onResume() {
    super.onResume();
    displayCafeNames();
  }

  private void displayCafeNames() {
    if (cafeNames != null && cafeNames.isEmpty()) {
      ProgressDialog dialog =
          ProgressDialog.show(VisitCafe.this, "", "Re-initializing. Please wait...", true);
      LoginTask loginTask = new LoginTask(dialog, VisitCafe.this);
      loginTask.execute();
    }

    if ((cafeNames == null || cafeNames.isEmpty()) && Main.cafePicker != null) {
      cafeNames = Main.cafePicker.getCafeNames(CafeListItem.getCafeNameServingMask(new LocalTime()));
      if (!cafeNames.isEmpty()) {
        setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
            cafeNames));
      }
    }
  }

  @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    final String cafeName = this.getListAdapter().getItem(position).toString();
    VisitDialog.display(cafeName, VisitCafe.this);
  }
}
